package com.example.codeReading.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.LightVirtualFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CodeSelectButton extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 1. 获取用户选中的数
//        String selectTxt = e.getDataContext().getData(PlatformDataKeys.EDITOR).getSelectionModel().getSelectedText();

        // 1. 获取选中文件的内容
        VirtualFile virtualFile = e.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE);
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(virtualFile.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException var1) {
            var1.printStackTrace();
            throw new RuntimeException(var1.getMessage());
        }
        System.out.print(content);
        // 创建一个新的虚拟文件
        LightVirtualFile virtualFile_new = new LightVirtualFile("new.txt", content);

        // 打开这个虚拟文件到右侧编辑区
        FileEditorManager editorManager = FileEditorManager.getInstance(e.getProject());
        editorManager.openFile(virtualFile_new, true);

        //
//        System.out.print(content);
    }
}
